<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Random;
use think\Config;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Session;
use think\Validate;
use app\common\model\User;
/**
 * 子级账户管理
 */
class Son extends Frontend
{

    protected $layout = 'default';
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $ucenter = get_addon_info('ucenter');
        if ($ucenter && $ucenter['state']) {
            include ADDON_PATH . 'ucenter' . DS . 'uc.php';
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 列表显示
    **/
    public function son(){

        //设置过滤方法
        $this->request->filter(['strip_tags']);

            $this->model = model('User');
            $map = [];
            // 判断是不是超级管理员
            if ( $this->auth->parent_id == 0 ){
                $map['parent_id'] = $this->auth->id;
                $map['status'] = 'normal';
            }else{
                $this->error('您不能进来');
            }

            $page=input('get.page/d',1);
            $list=$this->model->where($map)->order('id desc')->paginate(10,'',['page'=>$page]);
            $page2 = $list->render();
            return $this->view->fetch('',['list'=>$list,'page'=>$page2]);
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $this->model = model('User');
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        if ($this->request->isPost()){
            $password = $this->request->post("password");
            $token = $this->request->post('__token__');

            if ( $password ){
                $rule = [
                    'password'   => 'require|length:6,30',
                    '__token__'     => 'token',
                ];

                $msg = [];

                $data = [
                    'password'   => $password,
                    '__token__'     => $token,
                ];
                $field = [
                    'password'   => '新密码',
                ];

                $validate = new Validate($rule, $msg, $field);
                $result = $validate->check($data);
                if (!$result) {
                    $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                    return FALSE;
                }

                $salt = Random::alnum();
                $newpassword = $this->auth->getEncryptPassword($password, $salt);

                if ($this->model->where(['parent_id'=>$this->auth->id,'id'=>$ids])->update(
                    ['password' => $newpassword, 'salt' => $salt]
                )){
                    $this->success('修改成功','index/son/son');
                }else{
                    $this->error('修改失败');
                }
            }else{
                $this->error('如果你要修改密码请输入!!');

            }
        }

        return $this->view->fetch();
    }

    /**
     * 添加
    **/
    public function add(){
        // 添加
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $mobile = $this->request->post('mobile', '');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'mobile'    => 'regex:/^1\d{10}$/',
//                '__token__' => 'token',
            ];

            $msg = [
                'username.require' => '账户不能为空',
                'username.length'  => '账户长度为3,30',
                'password.require' => '密码不能为空',
                'password.length'  => '密码长度为6,30',
                'mobile'           => '号码不正确',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'mobile'    => $mobile,
//                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }

            if ( $ret = $this->register($username,$password,$mobile) !== TRUE){
                $this->error($ret);
            }else{
                $this->success('注册成功');
            }

        }

        return $this->view->fetch();
    }


    /**
     * 注册用户
     *
     * @param string $username  用户名
     * @param string $password  密码
     * @param string $email     邮箱
     * @param string $mobile    手机号
     * @param array $extend    扩展参数
     * @return boolean
     */
    private function register($username, $password, $mobile = '', $extend = [])
    {
        // 检测用户名或邮箱、手机号是否存在

        if (User::getByUsername($username))
        {
            return '用户已经存在';
        }

        if ($mobile && User::getByMobile($mobile))
        {
            return '号码已经存在';
        }

        $ip = request()->ip();
        $time = time();

        $data = [
            'username' => $username,
            'password' => $password,
            'mobile'   => $mobile,
            'level'    => 1,
            'score'    => 0,
            'avatar'   => '',
            'parent_id'=>$this->auth->id
        ];
        $params = array_merge($data, [
            'nickname'  => $username,
            'salt'      => Random::alnum(),
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ]);
        $params['password'] = $this->auth->getEncryptPassword($password, $params['salt']);
        $params = array_merge($params, $extend);


        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try
        {
            $user = User::create($params);
            Db::commit();

            //注册成功的事件
            return TRUE;
        }
        catch (Exception $e)
        {
            Db::rollback();
            return FALSE;
        }
    }


    /**
     * 删除
    **/
    public function status($ids){
        $this->model = model('User');
        if ($this->request->isPost() && $ids){
            if ($this->model->where(['parent_id'=>$this->auth->id,'id'=>$ids])->update(
                ['status' => 'Hidden']
            )){
                $this->success('删除成功');
            }

        }else{
            $this->error('id不能为空');
        }
    }


}
